﻿using System;
using System.Windows.Forms;
using Timer = System.Threading.Timer;

namespace XwOa
{
    public partial class Form1 : Form
    {
        #region 字段

        private string _userName;

        private string _password;

        private bool _autoSign;

        private TimeSpan _amSignIn;

        private TimeSpan _amSignOut;

        private TimeSpan _pmSignIn;

        private TimeSpan _pmSignOut;

        private Timer _autoSignTimer;

        private Status _status = Status.SignOut;

        private const string UrlHome = "http://v6.666gps.com:88";

        private const string UrlSign = "http://v6.666gps.com:88/LoginInfor.aspx";

        private const string UrlAddLog = "http://v6.666gps.com:88/AddLog.aspx";

        private bool _isSet;

        #endregion


        #region 属性

        public bool AutoSign
        {
            get { return _autoSign; }
            set
            {
                _autoSign = value;
                ConfigAppSettings.SetValue("AutoSign", value.ToString());
            }
        }

        public TimeSpan AmSignIn
        {
            get { return _amSignIn; }
            set
            {
                _amSignIn = value;
                ConfigAppSettings.SetValue("AmSignIn", value.ToString());
            }
        }

        public TimeSpan AmSignOut
        {
            get { return _amSignOut; }
            set
            {
                _amSignOut = value;
                ConfigAppSettings.SetValue("AmSignOut", value.ToString());
            }
        }

        public TimeSpan PmSignIn
        {
            get { return _pmSignIn; }
            set
            {
                _pmSignIn = value;
                ConfigAppSettings.SetValue("PmSignIn", value.ToString());
            }
        }

        public TimeSpan PmSignOut
        {
            get { return _pmSignOut; }
            set
            {
                _pmSignOut = value;
                ConfigAppSettings.SetValue("PmSignOut", value.ToString());
            }
        }

        public string UserName
        {
            get { return _userName; }
            set
            {
                _userName = value;
                ConfigAppSettings.SetValue("UserName", Decrypt.EncryptDes(value));
            }
        }

        public string Password
        {
            get { return _password; }
            set
            {
                _password = value;
                ConfigAppSettings.SetValue("Password", Decrypt.EncryptDes(value));
            }
        }

        #endregion


        public Form1()
        {
            InitializeComponent();
            
            InitAutoSign();
        }

        private void CheckAutoSign()
        {
            if (_autoSign)
            {
                if (_autoSignTimer == null)
                {
                    _autoSignTimer = new Timer(AutoSignCall, null, 0, 60000);
                }
            }
            else
            {
                if (_autoSignTimer != null)
                {
                    _autoSignTimer.Dispose();
                }
            }
        }

        private void InitAutoSign()
        {
            try
            {
                _amSignIn = TimeSpan.Parse(ConfigAppSettings.GetValue("AmSignIn"));
                _amSignOut = TimeSpan.Parse(ConfigAppSettings.GetValue("AmSignOut"));
                _pmSignIn = TimeSpan.Parse(ConfigAppSettings.GetValue("PmSignIn"));
                _pmSignOut = TimeSpan.Parse(ConfigAppSettings.GetValue("PmSignOut"));
                _autoSign = bool.Parse(ConfigAppSettings.GetValue("AutoSign"));
                _userName = Decrypt.DecryptDes(ConfigAppSettings.GetValue("UserName"));
                _password = Decrypt.DecryptDes(ConfigAppSettings.GetValue("Password"));
            }
            catch
            {
                btnAutoSign_Click(null, null);
                return;
            }

            if (_userName == "" || _password == "")
            {
                btnAutoSign_Click(null, null);
                return;
            }

            _isSet = true;
            CheckAutoSign();
        }

        private void GoHome()
        {
            wbXw.Url = new Uri(UrlHome);
        }

        private void SetValueById(string id, string value)
        {
            SetAttributeById("value", id, value);
        }

        private void FocusById(string id)
        {
            string js = string.Format("javascript:document.getElementById('{0}').focus()", id);
            wbXw.Navigate(js);
        }

        private void SetSelectedById(string id, int selectedIndex)
        {
            if (wbXw.Document == null || wbXw.Document.Body == null) return;
            HtmlElement select = wbXw.Document.All[id];
            if (select == null) return;
            HtmlElement option = select.All[selectedIndex];
            if (option != null) option.SetAttribute("selected", "selected");
        }

        private void SetAttributeById(string attributeName, string id, string value)
        {
            if (wbXw.Document == null || wbXw.Document.Body == null) return;
            HtmlElement element = wbXw.Document.All[id];
            if (element != null) element.SetAttribute(attributeName, value);
        }

        private void ClickById(string id)
        {
            string js = string.Format("javascript:document.getElementById('{0}').click()", id);
            wbXw.Navigate(js);
        }

        private void AutoSignCall(object sender)
        {
            TimeSpan now = DateTime.Now.TimeOfDay;
            double minutes = now.Subtract(_amSignIn).TotalMinutes;

            if (minutes < 0) return;

            //早上自动签到
            if (minutes < 1)
            {
                btnSignIn_Click(null, null);
                return;
            }

            minutes = now.Subtract(_amSignOut).TotalMinutes;

            if (minutes < 0) return;

            //上午自动签退
            if (minutes < 1)
            {
                btnSignOut_Click(null, null);
                return;
            }

            minutes = now.Subtract(_pmSignIn).TotalMinutes;

            if (minutes < 0) return;

            //下午自动签到
            if (minutes < 1)
            {
                btnSignIn_Click(null, null);
                return;
            }

            minutes = now.Subtract(_pmSignOut).TotalMinutes;

            if (minutes < 0) return;

            //下午自动签退
            if (minutes < 1)
            {
                btnSignOut_Click(null, null);
            }
        }

        private void Login()
        {
            SetValueById("MainContent_txtUserName", _userName);
            SetValueById("MainContent_txtPassword", _password);
            ClickById("MainContent_LoginButton");
        }

        #region 事件

        /// <summary>
        ///     上班签到
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSignIn_Click(object sender, EventArgs e)
        {
            _status = Status.NonLoginNonSignIn;
            GoHome();
        }

        /// <summary>
        ///     下班签退
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSignOut_Click(object sender, EventArgs e)
        {
            _status = Status.NonLoginNonSignOut;
            GoHome();
        }

        /// <summary>
        ///     新增日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddLog_Click(object sender, EventArgs e)
        {
            //_status = Status.NonLoginNonAddLog;
            //GoHome();
            if (XwOaHelper.Login(_userName, _password))
            {
                string s = WebHelper.GetPage(UrlAddLog);
                MessageBox.Show(s);
                //wbXw.Url = new Uri(UrlAddLog);
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            wbXw.GoBack();
        }

        private void btnForward_Click(object sender, EventArgs e)
        {
            wbXw.GoForward();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            wbXw.Refresh();
        }

        private void btnAutoSign_Click(object sender, EventArgs e)
        {
            FrmAutoSign autoSign;

            if (_isSet)
            {
                autoSign = new FrmAutoSign
                {
                    IsSet = _isSet,
                    UserName = _userName,
                    Password = _password,
                    AmSignIn = _amSignIn,
                    AmSignOut = _amSignOut,
                    PmSignIn = _pmSignIn,
                    PmSignOut = _pmSignOut,
                    AutoSign = _autoSign
                };
            }
            else
            {
                autoSign = new FrmAutoSign();
            }

            if (autoSign.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            UserName = autoSign.UserName;
            Password = autoSign.Password;
            AmSignIn = autoSign.AmSignIn;
            AmSignOut = autoSign.AmSignOut;
            PmSignIn = autoSign.PmSignIn;
            PmSignOut = autoSign.PmSignOut;
            AutoSign = autoSign.AutoSign;
            _isSet = true;
            autoSign.Dispose();
            CheckAutoSign();
        }

        private void wbXw_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (wbXw.Document == null || wbXw.Document.Window == null) return;

            switch (_status)
            {
                case Status.NonLoginNonSignIn:
                    _status = Status.NonSignIn;
                    Login();
                    break;
                case Status.NonSignIn:
                    _status = Status.SignIn;
                    wbXw.Url = new Uri(UrlSign);
                    break;
                case Status.SignIn:
                    _status = Status.Complete;
                    ClickById("MainContent_btnInsert");
                    break;
                case Status.NonLoginNonSignOut:
                    _status = Status.NonSignOut;
                    Login();
                    break;
                case Status.NonSignOut:
                    _status = Status.SignOut;
                    wbXw.Url = new Uri(UrlSign);
                    break;
                case Status.SignOut:
                    _status = Status.Complete;
                    ClickById("MainContent_btnInsert2");
                    break;
                case Status.NonLoginNonAddLog:
                    _status = Status.NonAddLog;
                    Login();
                    break;
                case Status.NonAddLog:
                    _status = Status.AddLog;
                    wbXw.Url = new Uri(UrlAddLog);
                    break;
                case Status.AddLog:
                    _status = Status.Complete;
                    SetSelectedById("MainContent_drpDiaryType", 3);
                    SetSelectedById("MainContent_drpWorkType", 1);
                    SetValueById("MainContent_txtBegin", "0830");
                    SetValueById("MainContent_txtEnd", "1000");
                    SetValueById("MainContent_txtExecution", "100");
                    FocusById("MainContent_txtDiary");
                    break;
            }
        }

        #endregion

    }

    enum Status
    {
        Complete,
        NonLoginNonSignOut,
        NonSignOut,
        SignOut,
        NonLoginNonSignIn,
        NonSignIn,
        SignIn,
        NonLoginNonAddLog,
        NonAddLog,
        AddLog
    }
}